/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.clinicplus.converter;

import br.com.foxline.clinicplus.service.AutocompleteService;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 *
 * @author luciano
 */
@ManagedBean(name="autocompleteconverter")
@RequestScoped
public class AutocompleteConverter implements Converter{

    @EJB
    private AutocompleteService autocompleteService;
    
    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if(value == null || value.equals("") || value.equals("null"))
            return null;
        Object get = component.getAttributes().get("value");
        if(get == null)
            return null;
        Class klass = get.getClass();
        return autocompleteService.find(klass, Long.parseLong(value));
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        Field field = getIdFromObject(value);
        field.setAccessible(true);
        Long id = new Long("0");
        try {
            id = (Long)field.get(value);
        } catch (IllegalArgumentException ex) {
            Logger.getLogger(AutocompleteConverter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(AutocompleteConverter.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        field.setAccessible(false);
        return "" + id ;
    }
    
    public Field getIdFromObject(Object o){
        Field[] fields = o.getClass().getDeclaredFields();
        for (Field field : fields) {
            if(field.getName().equals("id")){
                return field;
            }
        }
        return null;
    }
    
}
